//
//  FistTestViewController.m
//  安好
//
//  Created by qinlongqing on 14/11/25.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "FistTestViewController.h"
#import "Reachability.h"
#import "AFHTTPRequestOperationManager.h"
#import "CLDataBaseController.h"
#import "FistTestResultViewController.h"
#import "FistTestingManager.h"
#import <AVFoundation/AVFoundation.h>

@interface FistTestViewController ()<FistTestingManagerDelegate,AVAudioPlayerDelegate>
{
    UILabel *countDownTimeLabel;
    NSInteger timeCount;
    
    UIButton *goOnBTN;
    
    UILabel *timerCountLabel;
    
    AVAudioPlayer *startPlayer;
    AVAudioPlayer *finishPlayer;
    
    CGFloat imageViewHeight;
    CGFloat titleLabelHeight;
    CGFloat goOnBTNHeight;
}
@end

@implementation FistTestViewController

- (void)viewWillDisappear:(BOOL)animated{
    countDownTimeLabel.hidden = YES;
    countDownTimeLabel.alpha = 0;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self makeNavBar];
    
    [self.view setBackgroundColor:UIColorFromRGB(0x4fc1e9)];
    
    if (kScreenWidth == 414) {
        imageViewHeight = 240;
        titleLabelHeight = 96;
        goOnBTNHeight = 54;
    }
    else{
        imageViewHeight = 200;
        titleLabelHeight = 80;
        goOnBTNHeight = 45;
    }
    CGFloat space = (kScreenHeight - imageViewHeight - titleLabelHeight - goOnBTNHeight - 64)/4;
    
    
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.frame = CGRectMake((kScreenWidth - imageViewHeight)/2, space, imageViewHeight, imageViewHeight);
    imageView.image = [UIImage imageNamed:@"hui_quan_start"];
    [self.view addSubview:imageView];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    if (kScreenWidth == 414) {
        titleLabel.frame = CGRectMake(20, imageView.frame.origin.y + imageView.frame.size.height + space, kScreenWidth - 40, titleLabelHeight);
        titleLabel.font = [UIFont systemFontOfSize:17];
    }
    else{
        titleLabel.frame = CGRectMake(15, imageView.frame.origin.y + imageView.frame.size.height + space, kScreenWidth - 30, titleLabelHeight);
        titleLabel.font = [UIFont systemFontOfSize:15];
    }
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"手握手机，做用力挥拳动作，挥拳速度越快、频率越高、力量越大，得分越高";
    titleLabel.numberOfLines = 3;
    titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    titleLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:titleLabel];
    
    
    goOnBTN = [[UIButton alloc]init];
    goOnBTN.layer.cornerRadius = 3;
    if (kScreenWidth == 414) {
        goOnBTN.frame = CGRectMake(20, titleLabel.frame.origin.y + titleLabel.frame.size.height + space, kScreenWidth - 40, goOnBTNHeight);
        goOnBTN.titleLabel.font = [UIFont systemFontOfSize:22];
    }
    else{
        goOnBTN.frame = CGRectMake(15, titleLabel.frame.origin.y + titleLabel.frame.size.height + space, kScreenWidth - 30, goOnBTNHeight);
        goOnBTN.titleLabel.font = [UIFont systemFontOfSize:20];
    }
    goOnBTN.backgroundColor = [UIColor whiteColor];
    [goOnBTN setTitleColor:UIColorFromRGB(0x4fc1e9) forState:UIControlStateNormal];
    [goOnBTN setTitle:@"开始测试" forState:UIControlStateNormal];
    [goOnBTN addTarget:self action:@selector(doGoOnBTN) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:goOnBTN];
    
    //5s倒计时所需label
    countDownTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    CGPoint center = self.view.center;
    center.y -= 64;
    countDownTimeLabel.center = center;
    countDownTimeLabel.textColor = [UIColor redColor];
    countDownTimeLabel.font = [UIFont boldSystemFontOfSize:90];
    countDownTimeLabel.textAlignment = NSTextAlignmentCenter;
    countDownTimeLabel.text = @"1";
    countDownTimeLabel.hidden = YES;
    countDownTimeLabel.alpha = 0;
    [self.view addSubview:countDownTimeLabel];
    
    //5s倒计时后，显示10s测试时间的label
    timerCountLabel = [[UILabel alloc]init];
    if (kScreenWidth == 414) {
        timerCountLabel.frame = CGRectMake(20, titleLabel.frame.origin.y + titleLabel.frame.size.height + space, kScreenWidth - 40, titleLabelHeight);
        timerCountLabel.font = [UIFont boldSystemFontOfSize:20];
    }
    else{
        timerCountLabel.frame = CGRectMake(15, titleLabel.frame.origin.y + titleLabel.frame.size.height + space, kScreenWidth - 30, titleLabelHeight);
        timerCountLabel.font = [UIFont boldSystemFontOfSize:18];
    }
    timerCountLabel.textColor = [UIColor whiteColor];
    timerCountLabel.textAlignment = NSTextAlignmentCenter;
    timerCountLabel.backgroundColor = [UIColor clearColor];
    timerCountLabel.hidden = YES;
    [self.view addSubview:timerCountLabel];
    
    [FistTestingManager instance].delegate = self;
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)makeNavBar{
    self.navigationItem.title = @"挥拳";

    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(doBack)];
    [backBtnImg setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}

-(void)doBack{
    [startPlayer stop];
    [finishPlayer stop];
    [[FistTestingManager instance] stop];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)doGoOnBTN{
    goOnBTN.userInteractionEnabled = NO;
    
    timeCount = 5;
    
    countDownTimeLabel.text = [NSString stringWithFormat:@"%ld",timeCount];
    countDownTimeLabel.hidden = NO;
    countDownTimeLabel.alpha = 1;

    [self doAnimation];
}

- (void)doAnimation{
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.duration = 1.0;
    animationGroup.repeatCount = 1;//一直重复
    animationGroup.removedOnCompletion = YES;
    animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
    animationGroup.delegate = self;
    
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"];
    scaleAnimation.fromValue = @1.0;
    scaleAnimation.toValue = @2.0;
    scaleAnimation.duration = 1.0;
    
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.fromValue = @1.0;
    opacityAnimation.toValue = @0.0;
    opacityAnimation.duration = 1.0;
    
    animationGroup.animations = @[scaleAnimation,opacityAnimation];

    [countDownTimeLabel.layer addAnimation:animationGroup forKey:@"timeCountDown"];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if (timeCount == 1) {
        goOnBTN.userInteractionEnabled = YES;
        
        countDownTimeLabel.text = @"";
        countDownTimeLabel.hidden = YES;
        countDownTimeLabel.alpha = 0;
        [self testBegin];
    }
    else{
        timeCount -=1;
        
        countDownTimeLabel.text = [NSString stringWithFormat:@"%ld",timeCount];
        
        [self doAnimation];
        
        if (timeCount == 1) {
            [self performSelector:@selector(hiddenCountDownTimeLabel) withObject:nil afterDelay:0.8];
        }
    }
}

- (void)testBegin{
    [self playStart];//播放开始音乐
    //音乐播放完以后，在开始测试
    
//    goOnBTN.hidden = YES;
//    timerCountLabel.hidden = NO;
//    timerCountLabel.text = @"还剩10秒";
//    [[FistTestingManager instance] start];
}
- (void)playStart{
    NSString *fileName = [[NSBundle mainBundle] pathForResource:@"挥拳开始" ofType:@"mp3"];
    NSURL *fileUrl = [NSURL fileURLWithPath:fileName];
    NSError *error = nil;
    startPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    if (!startPlayer) {
        
    }
    else {
        [startPlayer setNumberOfLoops:0]; //默认为0，即播放一次就结束；如果设置为负值，则音频内容会不停的循环播放下去。
        startPlayer.delegate = self;
        [startPlayer play];
    }
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    if (flag && [player isEqual:startPlayer]) {
        goOnBTN.hidden = YES;
        timerCountLabel.hidden = NO;
        timerCountLabel.text = @"还剩10秒";
        [[FistTestingManager instance] start];
    }
}


- (void)testFinished{
    [self playFinish];//播放结束音乐
    
    goOnBTN.hidden = NO;
    timerCountLabel.hidden = YES;
}
- (void)playFinish{
    NSString *fileName = [[NSBundle mainBundle] pathForResource:@"挥拳结束" ofType:@"mp3"];
    NSURL *fileUrl = [NSURL fileURLWithPath:fileName];
    NSError *error = nil;
    finishPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    if (!finishPlayer) {
        
    }
    else {
        [finishPlayer setNumberOfLoops:0]; //默认为0，即播放一次就结束；如果设置为负值，则音频内容会不停的循环播放下去。
        [finishPlayer play];
    }
}


- (void)hiddenCountDownTimeLabel{
    countDownTimeLabel.text = @"";
    countDownTimeLabel.hidden = YES;
    countDownTimeLabel.alpha = 0;
}

- (void)doTimerCount:(NSInteger)timerCount{
    timerCountLabel.text = [NSString stringWithFormat:@"还剩%ld秒",10-timerCount];
}

- (void)loadTestResult:(NSDictionary *)testResult{
    [self testFinished];
    
    NSMutableDictionary *mTestResult = [[NSMutableDictionary alloc]initWithDictionary:testResult copyItems:YES];
    
    //判断是否登录,如果已登录：直接存入服务器。如果未登录：存入本地
    if ([[NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]] length] != 0) {//已登录
        NSInteger shakeCount = ((NSArray *)[mTestResult valueForKey:kHuiQuanTestDataArray]).count;
        if (shakeCount > 0) {
            [self showActionView];
            NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:kPlatform,@"platform",kVersion,@"version",@"10",@"type",[self setNewTime],@"daytime", nil];
            [parameters setValue:[NSString stringWithFormat:@"%ld",shakeCount] forKey:@"shake_fist"];
            [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kUploadHuiQuanTestDataURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSNumber * statusNum = [responseObject objectForKey:@"status"];
                NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
                NSString * statusString = [numberFormatter stringFromNumber:statusNum];
                if ([statusString isEqualToString:@"0"]) {
                    alertContent([responseObject objectForKey:@"msg"]);
                }else{
                    NSString *userName = [[UserManager shareInstance] getUserInfo].username;
                    [mTestResult setValue:userName forKey:kTestUserName];//得到当前用户的名字
                    
                    [self doShowTestResultView:mTestResult];
                }
                [self hiddenActionView];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self doShowTestResultView:mTestResult];
                [self hiddenActionView];
            }];
        }
        else{
            [self doShowTestResultView:mTestResult];
        }
    }
    else{//未登录
        [self doShowTestResultView:mTestResult];
    }
}

- (NSString *)setNewTime{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSInteger year = [dateComponent year];
    NSInteger month = [dateComponent month];
    NSInteger day = [dateComponent day];
    
    NSString *time = [NSString stringWithFormat:@"%ld-%ld-%ld",year,month,day];
    return time;
}

- (void)doShowTestResultView:(NSMutableDictionary *)dict{
    FistTestResultViewController *fistTestResult = [[FistTestResultViewController alloc]init];
    fistTestResult.testResultDict = dict;
    [self.navigationController pushViewController:fistTestResult animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
